package com.qqtop10.manager.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.qqtop10.manager.utils.oss.OSSFilePath;
import com.qqtop10.manager.utils.oss.OSSUploadUtils;

/**
 * 编辑器 上传图片 、 文件浏览
 * 
 * @author Jovi
 * @creation 2016年5月6日
 */
@RequestMapping("kindeditor")
@Controller
public class KindeditorController extends BaseController {

	private static final Logger logger = LoggerFactory
			.getLogger(KindeditorController.class);

	/**
	 * 图片上传(包括文件上传、flash上传、视频上传)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("upload.do")
	public void KindeditorUpload(HttpServletRequest request,
			@RequestParam MultipartFile[] imgFile, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-type", "text/html;charset=utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 项目存放图片目录
//		String rootPath = request.getSession().getServletContext()
//				.getRealPath("/")
//				+ File.separator
//				+ "static"
//				+ File.separator
//				+ "stepOver"
//				+ File.separator;
		String rootPath = "";
		// 根目录URL，可以指定绝对路径
		String rootUrl = request.getContextPath() + "/static/stepOver/";
		String result = "";
		String newFilename = "";
		try {
			// 获取文件类型
			String dirName = request.getParameter("dir");
			if (dirName != null) {
				if (!Arrays.<String> asList(
						new String[] { "image", "flash", "media", "file" })
						.contains(dirName)) {
					logger.info("无效的目录名称");
					return;
				}
				rootPath += dirName + "/";
				rootUrl += dirName + "/";
				File saveDirFile = new File(rootPath);
				if (!saveDirFile.exists()) {
					saveDirFile.mkdirs();
				}
			}
			// 根据相对路径产生articleRoot文件对象
			File articleRoot = new File(rootPath);
			// 如果文件夹不存在，那就创建一个
			if (!articleRoot.exists()) {
				articleRoot.mkdirs();
			}
			if (imgFile != null && imgFile.length != 0) {
				for (MultipartFile multipartFile : imgFile) {
					if (!multipartFile.isEmpty()) {
						String filename = multipartFile.getOriginalFilename();
						String lastName = filename.substring(filename
								.lastIndexOf(".") + 1);
						if (dirName.equals("image")) {
							if (!(lastName.equalsIgnoreCase("jpg")
									|| lastName.equalsIgnoreCase("jpeg")
									|| lastName.equalsIgnoreCase("png") || lastName
									.equalsIgnoreCase("gif")
									| lastName.equalsIgnoreCase("bmp"))) {
								result = "{\"error\":1,\"message\":\"上传失败！图片格式必须是(jpg | jpeg | png | gif | bmp)\"}";
								response.getWriter().write(result);
								return;
							}
						}
						newFilename = UUID.randomUUID() + "." + lastName;
						OSSUploadUtils client = new OSSUploadUtils();
						client.uploadFile(rootPath, newFilename, multipartFile);
						client.closeOssClient();
//						multipartFile.transferTo(new File(rootPath
//								+ File.separator + newFilename));
					}
					String url = "http://top10mall.oss-cn-beijing.aliyuncs.com/" + rootPath + newFilename;
					result = "{\"error\":0,\"url\" : \"" + url + "\"}";
					response.getWriter().write(result);
				}
			} else {
				result = "{\"error\":0,\"message\":\"上传失败：请选择图片\"}";
				response.getWriter().write(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			result = "{\"error\":0,\"message\":\"上传失败：" + e.getMessage()
					+ "\"}";
			response.getWriter().write(result);
		}

	}

	/**
	 * 文件管理
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("fileManage")
	public void fileManage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		// 项目存放图片目录
		String rootPath = request.getSession().getServletContext()
				.getRealPath("/")
				+ File.separator + "static" + File.separator;
		// 根目录URL，可以指定绝对路径
		String rootUrl = request.getContextPath() + "/static/";
		// 图片扩展名
		String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
		// 获取文件类型
		String dirName = request.getParameter("dir");
		if (dirName != null) {
			if (!Arrays.<String> asList(
					new String[] { "image", "flash", "media", "file" })
					.contains(dirName)) {
				logger.info("无效的目录名称");
				return;
			}
			rootPath += dirName + "/";
			rootUrl += dirName + "/";
			File saveDirFile = new File(rootPath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
		}
		// 根据path参数，设置各路径和URL
		String path = request.getParameter("path") != null ? request
				.getParameter("path") : "";
		// 当前路径
		String currentPath = rootPath + path;
		// 当前访问url
		String currentUrl = rootUrl + path;
		// 当前文件夹路径
		String currentDirPath = path;
		// 上一级文件夹路径
		String moveupDirPath = "";
		if (!"".equals(path)) {
			String str = currentDirPath.substring(0,
					currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0,
					str.lastIndexOf("/") + 1) : "";
		}

		// 排序方式
		String order = request.getParameter("order") != null ? request
				.getParameter("order").toLowerCase() : "name";

		// 不允许使用..移动到上一级目录
		if (path.indexOf("..") >= 0) {
			logger.info(" 不允许使用..移动到上一级目录");
			return;
		}
		// 最后一个字符不是/
		if (!"".equals(path) && !path.endsWith("/")) {
			logger.info("最后一个字符不是/");
			return;
		}
		// 目录不存在或不是目录
		File currentPathFile = new File(currentPath);
		if (!currentPathFile.isDirectory()) {
			logger.info("目录不存在或不是目录");
			return;
		}

		// 遍历目录取的文件信息
		List<Hashtable<?, ?>> fileList = new ArrayList<Hashtable<?, ?>>();
		if (currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				Hashtable<String, Object> hash = new Hashtable<String, Object>();
				String fileName = file.getName();
				if (file.isDirectory()) {
					hash.put("is_dir", true);
					hash.put("has_file", (file.listFiles() != null));
					hash.put("filesize", 0L);
					hash.put("is_photo", false);
					hash.put("filetype", "");
				} else if (file.isFile()) {
					String fileExt = fileName.substring(
							fileName.lastIndexOf(".") + 1).toLowerCase();
					hash.put("is_dir", false);
					hash.put("has_file", false);
					hash.put("filesize", file.length());
					hash.put("is_photo", Arrays.<String> asList(fileTypes)
							.contains(fileExt));
					hash.put("filetype", fileExt);
				}
				hash.put("filename", fileName);
				hash.put("datetime",
						new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file
								.lastModified()));
				fileList.add(hash);
			}
		}

		if ("size".equals(order)) {
			Collections.sort(fileList, new SizeComparator());
		} else if ("type".equals(order)) {
			Collections.sort(fileList, new TypeComparator());
		} else {
			Collections.sort(fileList, new NameComparator());
		}
		Map<String,Object> result = new HashMap<>();
		result.put("moveup_dir_path", moveupDirPath);
		result.put("current_dir_path", currentDirPath);
		result.put("current_url", currentUrl);
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);
		response.setContentType("application/json; charset=UTF-8");
		response.getWriter().write(super.result2Json(result, null));
	}

	/**
	 * 根据名称比较
	 * 
	 * @author Jovi
	 * @creation 2016年5月6日
	 */
	public class NameComparator implements Comparator<Object> {
		public int compare(Object a, Object b) {
			Hashtable<?, ?> hashA = (Hashtable<?, ?>) a;
			Hashtable<?, ?> hashB = (Hashtable<?, ?>) b;
			if (((Boolean) hashA.get("is_dir"))
					&& !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir"))
					&& ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String) hashA.get("filename"))
						.compareTo((String) hashB.get("filename"));
			}
		}
	}

	/**
	 * 根据大小比较
	 * 
	 * @author Jovi
	 * @creation 2016年5月6日
	 */
	public class SizeComparator implements Comparator<Object> {
		public int compare(Object a, Object b) {
			Hashtable<?, ?> hashA = (Hashtable<?, ?>) a;
			Hashtable<?, ?> hashB = (Hashtable<?, ?>) b;
			if (((Boolean) hashA.get("is_dir"))
					&& !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir"))
					&& ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				if (((Long) hashA.get("filesize")) > ((Long) hashB
						.get("filesize"))) {
					return 1;
				} else if (((Long) hashA.get("filesize")) < ((Long) hashB
						.get("filesize"))) {
					return -1;
				} else {
					return 0;
				}
			}
		}
	}

	/**
	 * 根据类型比较
	 * 
	 * @author Jovi
	 * @creation 2016年5月6日
	 */
	public class TypeComparator implements Comparator<Object> {
		public int compare(Object a, Object b) {
			Hashtable<?, ?> hashA = (Hashtable<?, ?>) a;
			Hashtable<?, ?> hashB = (Hashtable<?, ?>) b;
			if (((Boolean) hashA.get("is_dir"))
					&& !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir"))
					&& ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String) hashA.get("filetype"))
						.compareTo((String) hashB.get("filetype"));
			}
		}
	}

}
